package com.voice.call.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import voice.voice.call.cache.ConfigVosAccountCache;

import com.voice.call.common.Const;
import com.voice.call.entity.CallLog;
import com.voice.call.entity.VosAccount;
import com.voice.call.mapper.CallLogMapper;
import com.voice.call.service.CallVosBillService;
import com.voice.call.service.OpLogService;
import com.voice.call.service.UserAccountService;
import com.voice.call.service.VosCallBackService;
import com.voice.call.utils.DateUtil;
import com.voice.call.utils.StringUtil;

@Service
public class CallVosBillServiceImpl implements CallVosBillService{
	
	private static final Logger log = LoggerFactory.getLogger(CallVosBillServiceImpl.class);
	
	@Resource
	private ConfigVosAccountCache configVosAccountCache;
	
	@Resource
	private UserAccountService userAccountService;
	
	@Resource
	private OpLogService opLogService;
	
	@Resource
	private CallLogMapper  callLogMapper;
	
	@Resource
	private VosCallBackService  vosCallBackService;

	@Override
	public String getStatus(){
		return "CALL"; 
	}
	
	@Override
	public String getVosResponseText(String callInfo){
		 String[] arr = callInfo.split(",");
	 		//log.info("话单数组长度:{}",arr.length);
	 		if(arr !=null && arr.length >=49){
	 			
	 			String flowno = arr[41];
	 			//log.info("话单的唯一标识:{}",flowno);
	 			
	 			String caller = arr[0].replace("\"", ""); //主叫
	 			String callernum = arr[1].replace("\"", ""); //原始主叫
	 			String called = arr[3].replace("\"", ""); //原始被叫
	 			String orgionCalled = arr[2].replace("\"", "");
	 			
	 			String start_time = DateUtil.stampToDate(arr[19], DateUtil.DATE_TIME_FMT); //起始时间
	 			String stop_time = DateUtil.stampToDate(arr[20], DateUtil.DATE_TIME_FMT); //终止时间
	 			//String agentfeetime=arr[18]; //代理商计费时长(秒)
	 			String holdtime = arr[23]; //通话的时长(秒)
	 			//String feetime = arr[25]; //通话计费时长(秒)
	 			String reason = arr[48]; //终止原因
	 			String subreason = arr[47]; //挂断方
	 			
	 			String customeraccount = arr[32].replace("\"", "");//计费账户
	 			String customername = arr[33].replace("\"", "");//计费账户名称
	 			
	 			//log.info("customeraccount={}",customeraccount);
	 			VosAccount vosAccount = configVosAccountCache.getVosAccountForBillAccount(customeraccount);
	 			
	 			
	 			
	 			if(vosAccount!=null && vosAccount.getPhonePrefix()!=null){
	 				orgionCalled = orgionCalled.replaceAll("^"+vosAccount.getPhonePrefix(), ""); //计费的被叫号码
	 			}
	 			
	 			 if(vosAccount!=null&&customeraccount.equals(vosAccount.getBillAccount())){ 
	 				
	 				
	 				//log.info("通话的call_id:{}",call_id);
	 				log.info("通话的call_id:{}",flowno);
	 				log.info("通话的主叫:{}",caller);
	 				log.info("通话的原始主叫:{}",callernum);
	 				log.info("通话被叫号码:{}",orgionCalled);
	 				log.info("通话的原始被叫:{}",called);
	 				log.info("通话的起始时间:{}",start_time);
	 				log.info("通话的终止时间:{}",stop_time);
	 				//log.info("代理商计费时长(秒):{}",agentfeetime);
	 				log.info("通话的时长(秒):{}",holdtime);
	 				//log.info("通话计费时长(秒):{}",feetime);
	 				log.info("通话终止原因:{}",reason);
	 				log.info("通话挂断方:{}",subreason);
	 				log.info("通话计费账户:{}",customeraccount);
	 				log.info("通话计费账户名称:{}",customername);
	 				
	 				CallLog entity = new CallLog();
	 				entity.setEvent("callhangup");
	 				entity.setBillAcc(customeraccount);
	 				//entity.setCallId(call_id);
	 				entity.setCallId(flowno);
	 				entity.setCallType(0);
	 				entity.setCaller(caller);
	 				entity.setCallernum(callernum);
	 				
	 				if (orgionCalled.startsWith("00")) {
	 					entity.setCalled(orgionCalled);//通话被叫号码
					}else if(called.startsWith("00")){
						entity.setCalled(called);//通话被叫号码
					}else{
						entity.setCalled("00"+orgionCalled);//通话被叫号码
					}
	 				
	 				
	 				entity.setStartTime(start_time);
	 				entity.setStopTime(stop_time);
	 				entity.setLength(Integer.valueOf(holdtime));
	 				entity.setReason(Integer.valueOf(reason));
	 				entity.setSubreason(Integer.valueOf(subreason));
	 				if (!StringUtil.isEmpty(vosAccount.getMcc())&&vosAccount.getMcc().equals(Const.VOS_DEFAULT)) {
	 					entity.setStatus(Const.Y);
	 				}else {
	 					entity.setStatus(Const.N);
					}
	 				//entity.setUserData(Const.CALL_FROM_VOS);//表示vos话单
	 				
                   if (entity.getLength() == 0 && reason.equals("2")) { //拨打时长为0
	 					
                	    try {
                		   String  user_id=entity.getCallernum().replaceAll("[^0-9]+", "");
     	 				  //写日志
     	 				   opLogService.callWriteLog(Integer.valueOf(user_id), "vos","call error code:"+subreason, null, null);
						
						} catch (Exception e) {
							e.printStackTrace();
							log.error("电话拨打,写日志失败");
						}
						
					}
                   
                   
                   if (callBackBill(vosAccount,entity)) { //话单同步
                	   return flowno;
				   }
                   return null;
	 				
	 				
	 			}else{
	 				//log.info("非icall话单!");
	 			}
	 			
	 			
	 			
	 			return flowno;
	 			
	 		}
	 		return null;
	}
	
	private boolean callBackBill(VosAccount vosAccount,CallLog entity) {
		
		 if (!StringUtil.isEmpty(vosAccount.getMcc())&&vosAccount.getMcc().equals(Const.VOS_DEFAULT)) {
      	      return userAccountService.DeductionFreeWithCallLog(entity);
		 }else {
			 
			try {
				
				 entity.setCallerUid("");
			    int d = callLogMapper.insert(entity);
				if (d > 0) {
					log.info("callBackBill sgcall succcess");
					if (!StringUtil.isEmpty(vosAccount.getCalllogCallBack())) {
						vosCallBackService.visionCallBill(vosAccount.getCalllogCallBack(),entity); //同步第三方话单
					}
					return true;
				}else{
					log.error("callBackBill sgcall failed");
					return false;
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				if (!StringUtil.isEmpty(vosAccount.getCalllogCallBack())) {
					vosCallBackService.visionCallBill(vosAccount.getCalllogCallBack(),entity); //同步第三方话单
				}
				return true;
			}
				
		 }
	}
}
